<template>
  <div class="setting-wrapper">
    <ul class="setting-top">
      <li class="top-left">
        <el-button icon="el-icon-back" type="text" @click="back"
        >{{$t('common.base.back')}}</el-button
        >
        <!-- 默认模板直接展示固定文案，不做绑定，以免提交~ -->
        <el-input
          v-if="initParams.catalogId === 0"
          :disabled="true"
          :value="$t('superQrcode.defaultTemplate')"
        ></el-input>
        <el-input
          v-else
          :placeholder="$t('product.qrcodeSetting.text5')"
          v-model="productIntroduction"
        ></el-input>
      </li>
      <li class="top-center" @click="topClick">
        <span
          v-for="item in settingTop"
          :class="item.index === topIndex ? 'active' : ''"
          :key="item.index"
          :data-index="item.index"
        >{{ item.label }}</span
        >
      </li>
      <li class="top-right">
        <el-button @click="save">{{$t('common.base.save')}}</el-button>
      </li>
    </ul>
    <ul class="setting-bar">
      <li>{{$t('product.qrcodeSetting.text1')}}</li>
      <li class="bar-center">{{$t('product.qrcodeSetting.text2')}}</li>
      <li class="bar-right">{{$t('product.qrcodeSetting.text3')}}</li>
    </ul>
    <ul class="setting-bottom">
      <li class="btm-item btm-left">
        <p class="btm-left-title">{{ leftTitle }}</p>
        <draggable
          v-model="settingOptionsSystem"
          animation="300"
          :move="onMove"
          @end="moveEnd"
          filter=".forbid"
          ghost-class="ghost"
          chosen-class="chosen"
          :options="{ group: { name: 'itxst', pull: 'clone' }, sort: false }"
        >
          <transition-group class="drag-left">
            <div
              class="drag-left-item"
              v-for="item in settingOptionsSystem"
              :key="item.id"
              :class="item.dragged ? 'forbid' : ''"
              @click="dragClick(item)"
            >
              <i class="iconfont" :class="item.icon"></i>
              <p>{{ item.name }}</p>
            </div>
          </transition-group>
        </draggable>

        <template v-if="topIndex === 1">
          <p class="btm-left-title">{{$t('product.qrcodeSetting.text4')}}</p>
          <draggable
            v-model="settingOptionsSelf"
            animation="300"
            :move="onMove"
            @end="moveEnd2"
            filter=".forbid"
            ghost-class="ghost"
            chosen-class="chosen"
            :options="{ group: { name: 'itxst', pull: 'clone' }, sort: false }"
          >
            <transition-group class="drag-left">
              <div
                class="drag-left-item"
                v-for="(item,index) in settingOptionsSelf"
                :key="item.id"
                :class="item.dragged ? 'forbid' : ''"
                @click="dragClick(item)"
              >
                <i class="iconfont" :class="item.icon"></i>
                <p>{{ item.name }}</p>
              </div>
            </transition-group>
          </draggable>
        </template>
      </li>
      <li class="btm-item btm-center" ref="btmCenter">
        <div class="btm-center-phone" ref="centerPhone">
          <draggable
            v-model="settingOptions2"
            animation="300"
            class="drag-right-wrap"
            group="itxst"
            :move="onMove"
          >
            <transition-group class="drag-right">
              <template v-if="phoneShow">
                <phone-content
                  v-for="(item, index) in settingOptions2"
                  :key="item.id + index"
                  :ref="'phone_' + item.id"
                  :top-index="topIndex"
                  :event-list="eventList"
                  :paas-list="paasList"
                  :option="item"
                  :select-id="selectId"
                  :scroll-flag="scrollFlag"
                  :product-card-list="productCardList"
                  @selectItem="selectItem"
                  :show-fields="showFields"
                  :com-data="comData"
                  :company-info="companyInfo"
                  :image-array="imageArray[item.id]"
                  :filter-fields="filterFields"
                  :project-info="projectInfo"
                />
              </template>
            </transition-group>
          </draggable>
        </div>
        <div
          class="btm-center-name"
          :style="delStyle"
          v-show="selectId"
          ref="btnCenterName"
          @click="delItem(selectId)"
        >
          {{ nowOption.name }}
          <i
            class="iconfont icon-delete"
            v-if="selectId !== 'productInformation'"
          ></i>
        </div>
      </li>
      <li class="btm-item btm-right">
        <template v-if="selectId">
          <right-component
            ref="rightComPonentRef"
            v-if="rightFlag === 2"
            :now-option="nowOption"
            :all-event-list="allEventList"
            :event-id-list="eventIdList"
            :paas-list="paasList"
            :show-fields="showFields"
            :project-info="projectInfo"
            :product-card-list="productCardList"
            @changeEvent="changeEvent"
            :rules="rules"
            :image-array="imageArray[selectId]"
            :customer-service-name="customerServiceName"
            :wechat-service-url="wechatServiceUrl"
            :progress-query="progressQuery"
            :enterprise-mall="enterpriseMall"
            @checkRule="checkRule"
            @upload="uploadSuc"
            @delImage="delImage"
            @link="link"
            @changeTitle="changeTitle"
            @titleShow="titleShow"
            @configChange="configChange"
            @isShowProductRecord="isShowProductRecord"
            @changeState="changeState"
            @itemAttrChange="itemAttrChange"
            @updateCustomerServiceName="updateCustomerServiceName"
            @updateWechatServiceUrl="updateWechatServiceUrl"
            @updateSelfService="updateSelfService"
            @multiLang="multiLang"
            @changePaas="changePaas"
            @updateProjectInfo="updateProjectInfo"
            @updateProductCard="updateProductCard"
          ></right-component>
        </template>
      </li>
    </ul>

    <rule-dialog
      :rule-dialog="ruleDialog"
      :rule-form="ruleForm"
      :user-list="userList"
      @close="ruleDialogClose"
    ></rule-dialog>
    <last-dialog
      :last-show="lastShow"
      :last-form="lastForm"
      :tenant-id="tenantId"
      @close="lastClose"
    ></last-dialog>
  </div>
</template>

<script>
import locales from '@src/locales';
import _ from 'lodash'
import { isEmpty } from '@src/util/type'
import draggable from 'vuedraggable'
import { randomString } from 'pub-bbx-utils'
import phoneContent from './component/phoneContent'
import rightComponent from './component/rightComponent'
import {
  queryEventType,
  queryCompanyInfo,
  saveSuperCodeTemplate,
  getShowFields,
  querySettingRules,
  queryRuleInfo,
  getSuperCodePaasInfo,
} from '@src/api/SuperQrcode'

import {
  getConfig
} from '@src/api/ProductV2Api';
import { getOssUrl } from '@src/util/assets'
const MAP_MARKER = getOssUrl('/marker.png')
import ruleDialog from './component/ruleDialog'
import lastDialog from './component/lastDialog'
import { getCompanyInfo } from '@src/api/PortalApi.ts'
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum';
import { useTenantId } from '@hooks/useRootWindow.ts';
let map = null

export default {
  name: 'super-qrcode',
  inject: ['initData'],
  data() {
    return {
      rightFlag: 0,
      tenantId: '',
      topIndex: 1,
      comData: {
        tenantName: '',
        attribute: {},
      },
      settingTop: [
        { label: this.$t('product.qrcodeSetting.text6'), index: 1 },
        // { label: '配置企业', index: 2 },
        // { label: '配置商城', index: 3 },
      ],
      productIntroduction: '',
      settingIndex: [
        {
          id: 'productPicture',
          name: this.$t('common.form.preview.relatedProduct.label2'),
          icon: 'icon-image-fill2',
          side: 'left',
          dragged: false,
        },
        {
          id: 'productIntroduction',
          name: this.$t('common.form.preview.relatedProduct.label1'),
          icon: 'icon-edit-fill',
          side: 'left',
          dragged: false,
          title: this.$t('common.form.preview.relatedProduct.label1'),
          notShowTitle: false,
        },
        {
          id: 'selfService',
          name: this.$t('product.qrcodeSetting.selfService'),
          icon: 'icon-fuwu-xuanzhong',
          side: 'left',
          dragged: false,
          title: this.$t('product.qrcodeSetting.selfService'),
          notShowTitle: false,
          isGetProductEventList: false,
          isSelectSelfHelp: 0
        },
        {
          id: 'productInformation',
          name: this.$t('product.qrcodeSetting.text7'),
          icon: 'icon-caidan-chanpin1',
          side: 'left',
          dragged: true,
          title: this.$t('product.qrcodeSetting.text7'),
          notShowTitle: false,
        },
        {
          id: 'productVideo',
          name: this.$t('product.qrcode.type.productVideo'),
          icon: 'icon-video-fill',
          side: 'left',
          dragged: false,
          title: this.$t('product.qrcode.type.productVideo'),
          notShowTitle: false,
        },
        {
          id: 'productInstructions',
          name: this.$t('common.form.preview.relatedProduct.label3'),
          icon: 'icon-book-fill',
          side: 'left',
          dragged: false,
          title: this.$t('common.form.preview.relatedProduct.label3'),
          notShowTitle: false,
          onlyCustomerLinkmanShow: 0
        },
        {
          id: 'onlineService',
          name: this.$t('common.base.onlineService'),
          icon: 'icon-phone-fill',
          side: 'left',
          dragged: false,
          title: this.$t('common.base.onlineService'),
          notShowTitle: false,
        },
        {
          id: 'knowledgeBase',
          name: this.$t('product.productWiki'),
          icon: 'icon-book-fill',
          side: 'left',
          dragged: false,
          title: this.$t('product.productWiki'),
          notShowTitle: false,
          onlyCustomerLinkmanShow: 0
        },
        {
          id: 'productPart',
          name: this.$t('product.productPart'),
          icon: 'icon-beijian',
          side: 'left',
          dragged: false,
          title: this.$t('product.productPart'),
          notShowTitle: false,
          onlyCustomerLinkmanShow: 0
        },
        {
          id: 'images',
          name: this.$t('common.base.image'),
          icon: 'icon-image-fill2',
          side: 'left',
          dragged: false,
          title: this.$t('common.base.image'),
          notShowTitle: false,
        },
        {
          id: 'productRegister',
          name: this.$t('common.base.productRegister'),
          icon: 'icon-caidan-chanpin1',
          side: 'left',
          draggeds: false,
          title: this.$t('product.qrcodeSetting.text8'),
          notShowTitle: false,
        },
        {
          id: 'companyInfo',
          name: this.$t('common.pageTitle.pageAccountCompany'),
          icon: 'icon-qiye-tianchong',
          side: 'left',
          dragged: false,
          title: this.$t('product.qrcodeSetting.text9'),
          notShowTitle: false,
        }, 
        {
          id: 'projectManage',
          name: this.$t('common.base.projectManage'),
          icon: 'icon-qiye-tianchong',
          side: 'left',
          dragged: false,
          title: this.$t('common.base.projectManage'),
          notShowTitle: false,
        },
        {
          id: 'productCard',
          name: this.$t('product.qrcodeSetting.productCard'),
          icon: 'icon-fujiazujian1',
          side: 'left',
          dragged: false,
          title: this.$t('product.qrcodeSetting.productCard'),
          notShowTitle: false,
        },
      ],
      settingIndex2: [
        {
          id: 'productInformation',
          name: this.$t('product.qrcodeSetting.text7'),
          icon: 'icon-caidan-chanpin1',
          side: 'right',
          dragged: false,
          title: this.$t('product.qrcodeSetting.text7'),
          notShowTitle: false,
        },
      ],
      settingCom: [
        {
          id: 'enterpriseInformation',
          name: this.$t('product.qrcodeSetting.text10'),
          icon: 'icon-qiye-tianchong',
          side: 'left',
          dragged: false,
          title: this.$t('product.qrcodeSetting.text10'),
          notShowTitle: false,
        },
      ],
      settingCom2: [],
      settingMall: [
        {
          id: 'onlineMall',
          name: this.$t('product.qrcodeSetting.onlineMall'),
          icon: 'icon-shop-fill',
          side: 'left',
          dragged: false,
          title: this.$t('product.qrcodeSetting.onlineMall'),
          notShowTitle: false,
        },
      ],
      settingMall2: [],
      showFields: [],
      selectId: null,
      nowOption: {
        name: '',
        title: '',
        displayNameLanguage: null
      },
      delStyle: '',
      clientRect: null,
      scrollFlag: false,

      allEventList: [],
      eventList: [],
      eventIdList: [],
      rules: [],

      comFirst: true, // 是否第一次点击配置企业
      initParams: {},

      ruleDialog: false,
      ruleForm: {
        distributeCondition: {},
      },
      userList: [],
      lastShow: false,
      lastForm: {},

      imageArray: {},
      phoneShow: true,

      isOpenRegister: true,
      filterFields: [],
      customerServiceName: 'shb',
      wechatServiceUrl: '',
      companyInfo: {},
      progressQuery: false,
      enterpriseMall: true,
      paasList: [],
      projectInfo: {
        projectFieldData: [],
        taskFieldData: [],
      },
      productCardList: [],
    }
  },
  computed: {
    leftTitle() {
      if (this.topIndex === 1) return this.$t('product.qrcodeSetting.text11')
      else if (this.topIndex === 2) return this.$t('product.qrcodeSetting.text12')
      return this.$t('product.qrcodeSetting.text13')
    },
    settingOptions() {
      if (this.topIndex === 1) {
        return this.isOpenRegister ? this.settingIndex : this.settingIndex.filter(v => v.id !== 'productRegister')
        // return this.settingIndex
      } else if (this.topIndex === 2) {
        return this.settingCom
      } 
      return this.settingMall
      
    },
    settingOptionsSystem() {
      return this.settingOptions.filter(v => !['images', 'productRegister'].includes(v.id))
    },
    settingOptionsSelf() {
      return this.settingOptions.filter(v => ['images', 'productRegister'].includes(v.id))
    },
    settingOptions2: {
      get() {
        if (this.topIndex === 1) {
          return this.settingIndex2
        } else if (this.topIndex === 2) {
          return this.settingCom2
        } 
        return this.settingMall2
        
      },
      set(v) {
        if (this.topIndex === 1) {
          this.settingIndex2 = v
        } else if (this.topIndex === 2) {
          this.settingCom2 = v
        } else {
          this.settingMall2 = v
        }
      },
    },
    tenantId() {
      return useTenantId();
    },
  },
  watch: {
    topIndex(val) {
      if (val === 2) {
        this.initMap()
      } else {
        map && map.destroy()
      }
    },
  },
  mounted() {
    this.tenantId = window.sessionStorage.getItem('qrcode_set_tenantId')
    this.initParams = JSON.parse(
      window.sessionStorage.getItem('edit_qrcode_template_params')
    )
    console.log('this.initParams',this.initParams)
    this.lastForm = this.initParams.lastForm || {}
    for (let key in this.initParams.setting) {
      if (key.includes('images')) {
        this.$set(
          this.imageArray,
          key,
          this.initParams.setting[key]?.imageArray
        )
      }

      if (key.includes('onlineService')) {
        this.customerServiceName = this.initParams.setting[key]?.customerServiceName || 'shb';
        this.wechatServiceUrl = this.initParams.setting[key]?.wechatServiceUrl || '';
      }

      if (key.includes('selfService')) {
        this.progressQuery = this.initParams.setting[key]?.progressQuery ?? false;
        this.enterpriseMall = this.initParams.setting[key]?.enterpriseMall ?? true;
      }
      // 处理回显项目管理
      if (key.includes('projectManage')) {
        this.projectInfo.projectFieldData = this.initParams.setting[key].projectFieldList || [];
        this.projectInfo.taskFieldData =  this.initParams.setting[key].ProjectTaskFieldList || [];
      }
      // 处理回显产品附加组件
      if (key.includes('productCard')) {
        this.productCardList = this.initParams.setting[key].productCardList || [];
      }
    }
    // this.imageArray=this.initParams.setting.images?.imageArray || [];
    this.$refs.centerPhone.addEventListener('scroll', this.handleScroll)
    this.queryEventType('')
    this.getSuperCodePaasInfoReq()
    if (this.initParams.doorEventType) {
      this.eventIdList = this.initParams.doorEventType.map((item) => item)
    }
    if (this.initParams.showFields) {
      this.showFields = this.initParams.showFields
    }
    this.getShowFields()
    this.querySettingRules()
    this.getCompanyInfo();

    this.isOpenRegisterCheck()
  },
  methods: {
    /** 更新产品附件组件*/
    updateProductCard(value) {
      this.productCardList = value
    },
    /** 更新项目信息*/
    updateProjectInfo(value) {
      this.projectInfo = value
    },
    // 获取公司信息
    async getCompanyInfo() {
      try {
        const { code, result } = await getCompanyInfo();
        if (code !== 0) return;

        this.companyInfo = result;
      } catch (error) {
        console.error('getCompanyInfo error', error);
      }
    },
    isOpenRegisterCheck() {
      getConfig({
        configCode: [
          'PRODUCT_REGISTRATION'
        ]
      }).then(res => {
        if(res.errorCode === 0) {
          this.isOpenRegister = !!res?.data[0]?.isOpen
          !this.isOpenRegister && this.filterFields.push('productRegister')
        }
      })
    },
    // 修改标题
    changeTitle(val) {
      this.phoneShow = false
      const item = this.settingOptions2.find(
        (item) => item.id === this.nowOption.id
      )
      if (!item) {
        this.$nextTick(() => {
          this.phoneShow = true
        })
        return
      }
      item.title = val
      this.nowOption.title = val
      item.displayNameLanguage && (item.displayNameLanguage[locales.locale] = val);
      this.nowOption.displayNameLanguage && (this.nowOption.displayNameLanguage[locales.locale] = val);
      this.$nextTick(() => {
        this.phoneShow = true
      })
    },
    // 设置标题是否可显示
    titleShow(val) {
      this.phoneShow = false
      const item = this.settingOptions2.find(
        (item) => item.id === this.nowOption.id
      )
      if (item) item.notShowTitle = val
      this.nowOption.notShowTitle = val
      this.$nextTick(() => {
        this.phoneShow = true
      })
    },
    configChange([name, val]) {
      this.phoneShow = false
      const item = this.settingOptions2.find(
        (item) => item.id === this.nowOption.id
      )
      if (item) item[name] = val
      this.nowOption[name] = val
      this.$nextTick(() => {
        this.phoneShow = true
      })
    },
    isShowProductRecord(val) {
      this.phoneShow = false
      const item = this.settingOptions2.find(
        (item) => item.id === this.nowOption.id
      )
      if (item) item.isGetProductEventList = val
      this.nowOption.isGetProductEventList = val
      this.$nextTick(() => {
        this.phoneShow = true
      })
    },
    changeState(val) {
      this.phoneShow = false
      const item = this.settingOptions2.find(
        (item) => item.id === this.nowOption.id
      )
      if (item) item.isSelectSelfHelp = val
      this.nowOption.isSelectSelfHelp = val
      this.$nextTick(() => {
        this.phoneShow = true
      })
    },
    // 配置链接
    link(url, id) {
      const file = this.imageArray[this.selectId].find((item) => item.id === id)
      file.linkUrl = url
    },
    // 删除图片
    delImage(id) {
      const index = this.imageArray[this.selectId].findIndex(
        (item) => item.id === id
      )
      this.imageArray[this.selectId].splice(index, 1)
    },
    // 上传成功
    uploadSuc(item) {
      this.imageArray[this.selectId].push(item)
    },
    // 关闭保底弹框
    lastClose(bool, form) {
      this.lastShow = false
      if (bool === true) {
        this.lastForm.phone = form.phone
        this.lastForm.wxAccount = form.wxAccount
        this.save()
      }
    },
    // 关闭规则弹框
    ruleDialogClose() {
      this.ruleDialog = false
    },
    // 查看规则
    async checkRule(id) {
      try {
        let res = await queryRuleInfo({ id })
        if (res.code === '200') {
          this.ruleDialog = true
          this.ruleForm = res.data
          if (this.ruleForm.candidate) {
            this.userList = this.ruleForm.candidate.info.map(
              (item) => item.userName
            )
          }
          const distributeCondition = this.ruleForm.distributeCondition
          if (
            distributeCondition.apply === 'product'
            && distributeCondition.fieldName === 'type'
          ) {
            distributeCondition.option = distributeCondition.pathName
          }
        } else {
          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: res.msg,
            duration: 2000,
          })
        }
      } catch (err) {
        console.error(err)
      }
    },
    // 获取已开启规则
    async querySettingRules() {
      try {
        const params = {
          tenantId: this.tenantId,
          enabled: 1,
        }
        let res = await querySettingRules(params)
        if (res.code === '200') {
          this.rules = res.data
        } else {
          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: res.msg,
            duration: 2000,
          })
        }
      } catch (err) {
        console.error(err)
      }
    },
    // 编辑时初始化数据
    initEditData() {
      const setting = this.initParams.setting
      this.productIntroduction = this.initParams.productIntroduction || this.$t('product.qrcodeSetting.text14')
      let indexList = [],
        imagesList = [],
        comList = [],
        mallList = []
      Object.keys(setting).forEach((key) => {
        const indexItem = this.settingIndex.filter(
          (item) => item.id === key && !item.id.includes('images')
        )
        const imagesItem = this.settingIndex.filter(
          (item) => item.id === 'images'
        )
        const copy = Object.assign({}, imagesItem)
        if (copy && key.includes('images')) {
          copy.id = key
          copy.order = setting[key].order
          copy.title = setting[key]?.displayNameLanguage?.[locales.locale] || setting[key].title
          copy.notShowTitle = setting[key].notShowTitle
          copy.displayNameLanguage = setting[key].displayNameLanguage
          indexList.push(copy)
        }
        if (!isEmpty(indexItem)) {
          indexItem.id = key
          indexItem.order = setting[key].order
          indexItem.title = setting[key]?.displayNameLanguage?.[locales.locale] || setting[key].title
          indexItem.notShowTitle = setting[key].notShowTitle
          indexItem.displayNameLanguage = setting[key].displayNameLanguage
          if (['productPart', 'knowledgeBase', 'productInstructions'].includes(key)) {
            indexItem.onlyCustomerLinkmanShow = setting[key].onlyCustomerLinkmanShow || 0
          }
          if (indexItem.id === 'productRegister') {
            indexItem.ifRegisterGuide = setting[key].ifRegisterGuide
          }
          if (indexItem.id === 'selfService') {
            indexItem.isGetProductEventList = setting[key].isGetProductEventList
            indexItem.isSelectSelfHelp = setting[key].isSelectSelfHelp
          }
          indexList.push(indexItem)
        }
        const comItem = this.settingCom.find((item) => item.id === key)
        if (!isEmpty(comItem)) {
          comItem.id = key
          comItem.order = setting[key].order
          comItem.title = setting[key]?.displayNameLanguage?.[locales.locale] || setting[key].title
          comItem.notShowTitle = setting[key].notShowTitle
          comItem.displayNameLanguage = setting[key].displayNameLanguage
          comList.push(comItem)
        }
        const mallItem = this.settingMall.find((item) => item.id === key)
        if (!isEmpty(mallItem)) {
          mallItem.id = key
          mallItem.order = setting[key].order
          mallItem.title = setting[key]?.displayNameLanguage?.[locales.locale] || setting[key].title
          mallItem.notShowTitle = setting[key].notShowTitle
          mallItem.displayNameLanguage = setting[key].displayNameLanguage
          mallList.push(mallItem)
        }
      })
      this.initSelectedData(indexList, this.settingIndex, this.settingIndex2)
      // this.initSelectedData(imagesList,this.settingIndex,this.settingIndex2);
      this.initSelectedData(comList, this.settingCom, this.settingCom2)
      this.initSelectedData(mallList, this.settingMall, this.settingMall2)
    },
    // 编辑时构造已选数据
    initSelectedData(list, settingList, settingList2) {
      list.sort((a, b) => a.order - b.order)
      list.forEach((item, index) => {
        let leftItem
        leftItem = settingList.find((s) => s.id === item.id)
        if (item.id.includes('images')) {
          leftItem = settingList.find((s) => s.id === 'images')
        }
        leftItem.dragged = leftItem.id !== 'images'
        settingList2[index] = {
          id: item.id,
          name: leftItem.name,
          icon: leftItem.icon,
          title: item.title,
          displayNameLanguage: item.displayNameLanguage,
          notShowTitle: item.notShowTitle,
          side: 'right',
          dragged: false,
        }
        if (['productPart', 'knowledgeBase', 'productInstructions'].includes(item.id)) {
          settingList2[index].onlyCustomerLinkmanShow = item.onlyCustomerLinkmanShow || 0
        }
        if (item.id === 'productRegister') {
          settingList2[index].ifRegisterGuide = item.ifRegisterGuide
        }
        if (item.id === 'selfService') {
          settingList2[index].isGetProductEventList = item.isGetProductEventList
          settingList2[index].isSelectSelfHelp = item.isSelectSelfHelp
        }
        if (leftItem.id === 'productInformation') {
          this.initParams.showFields.forEach((obj) => {
            for (let key in obj) {
              const showField = this.showFields.find(
                (item) => item.fieldName === key
              )
              if (showField) showField.showFlag = '1'
            }
          })
        }
      })
    },
    // 获取所有产品字段
    async getShowFields() {
      try {
        let { code, data=[], msg } = await getShowFields({
          tenantId: this.tenantId,
        })
        if (code === '200') {
          this.showFields = data.filter(f=>f.formType !== FieldTypeMappingEnum.JsCodeBlock)
          if (this.initParams.setting) this.initEditData()
          this.rightFlag++
        } else {
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.toast'),
            message: msg,
          })
        }
      } catch (err) {
        console.error(err)
      }
    },
    // 保存前先检测
    check() {
      const onlineService = this.settingOptions2.find(
        (item) => item.id === 'onlineService'
      )
      if (onlineService && !this.lastForm.phone) {
        this.lastShow = true
      } else {
        this.save()
      }
    },
    // 保存
    async save() {
      try {
        // 产品附加组件校验
        const isHaveProductCard = this.settingIndex2.some(item => item.id === 'productCard');
        if (isHaveProductCard) {
          if(this.productCardList.length == 0){
            return this.$message({
              type: 'warning',
              message: this.$t('product.setting.qrCodeSet.createTemplate.ProductCardPlaceholder'),
            })
          }
          const hasEmptyNameValue = this.productCardList.some(obj => Object.keys(obj.cardField).length == 0);
          const hasEmptyLinkerValue = this.productCardList.some(obj => obj.cardLinkerField.length == 0);
          if(hasEmptyNameValue || hasEmptyLinkerValue) {
            return this.$message({
              type: 'warning',
              message: this.$t('product.qrcodeSetting.paasApplyTemplate.msg'),
            })
          }
        }
      
        // 当项目管理存在时校验必须选择项目展示信息
        const isHaveProjectManage = this.settingIndex2.some(item => item.id === 'projectManage');
        if (isHaveProjectManage && this.projectInfo.projectFieldData.length == 0) {
          return this.$message({
            type: 'warning',
            message: this.$t('product.setting.qrCodeSet.createTemplate.projectPlaceholder'),
          })
        }

        if (!this.productIntroduction) {
          return this.$message({
            type: 'warning',
            message: this.$t('product.setting.qrCodeSet.createTemplate.tips1'),
          })
        }
        if (this.productIntroduction.length > 100) {
          return this.$message({
            type: 'warning',
            message: this.$t('product.qrcodeSetting.text15', {num1: '100'}),
          })
        }
        // if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(this.productIntroduction)) {
        //   return this.$message({
        //     type: 'warning',
        //     message: this.$t('product.qrcodeSetting.text16'),
        //   })
        // }
        const settingIndex2 = this.settingIndex2
        const settingCom2 = this.settingCom2
        const settingMall2 = this.settingMall2
        const selfService = settingIndex2.find(
          (item) => item.id === 'selfService'
        )
        const onlineService = this.settingOptions2.find(
          (item) => item.id === 'onlineService'
        )
        if (onlineService && this.customerServiceName === 'wx') {
          const hasWxAuth = sessionStorage.getItem('hasWxAuth');
          if (!hasWxAuth) {
            return this.$message({
              type: 'warning',
              message: this.$t('product.qrcodeSetting.text18'),
            })
          }

          if (!this.wechatServiceUrl) {
            return this.$message({
              type: 'warning',
              message: this.$t('product.qrcodeSetting.text19'),
            })
          }
        }
        if (onlineService && !this.lastForm.phone) return (this.lastShow = true)
        let params = {
          id: this.initParams.id,
          tenantId: this.tenantId,
          showFields: '',
          setting: {},
          catalogId: this.initParams.catalogId,
          productIntroduction: this.productIntroduction,
        }
        params.showFields = this.showFields
          .filter((item) => item.showFlag)
          .map((item) => {
            return {
              [item.fieldName]: item.displayName,
              isSystem: item.isSystem,
              formType: item.formType,
              setting: item.setting
            }
          })
        if (selfService) {
          if (this.eventIdList.length === 0 && this.paasList.length == 0 ) {
            return this.$message({
              type: 'warning',
              message: this.$t('product.qrcodeSetting.text17'),
            })
          }
          params.doorEventType = this.eventIdList;
          if(this.paasList.length>0){
            params.doorPaasInfo = this.paasList;
            const hasEmptyNameValue = this.paasList.some(obj => !obj.applicationName);
            const hasEmptyPassValue = this.paasList.some(obj => !obj.templateBizId);
            const hasEmptycusstomerLinkValue = this.paasList.some(obj => obj.templateBizId === 'CustomLink' && !obj.cusstomerLink);
            if(hasEmptyNameValue || hasEmptyPassValue || hasEmptycusstomerLinkValue) {
              return this.$message({
                type: 'warning',
                message: this.$t('product.qrcodeSetting.paasApplyTemplate.msg'),
              })
            }
          }
        }
        settingIndex2.forEach((item, index) => {
          params.setting[item.id] = {
            isOpen: 1,
            order: index + 1,
            title: item.title,
            notShowTitle: item.notShowTitle || false,
          }
          if(item.displayNameLanguage){
            params.setting[item.id].displayNameLanguage = item.displayNameLanguage
          }
          if (['productPart', 'knowledgeBase', 'productInstructions'].includes(item.id)) {
            params.setting[item.id].onlyCustomerLinkmanShow = item.onlyCustomerLinkmanShow || 0
          }
          if (item.id.includes('images')) {
            params.setting[item.id].imageArray = this.imageArray[item.id]
          }
          if (item.id === 'productRegister') {
            params.setting[item.id].ifRegisterGuide = item.ifRegisterGuide
          }
          if (item.id === 'onlineService') {
            params.setting[item.id].customerServiceName = this.customerServiceName;
            params.setting[item.id].wechatServiceUrl = this.wechatServiceUrl;
          }
          if (item.id === 'selfService') {
            params.setting[item.id].isGetProductEventList = item.isGetProductEventList
            params.setting[item.id].isSelectSelfHelp = item.isSelectSelfHelp
            params.setting[item.id].progressQuery = this.progressQuery;
            params.setting[item.id].enterpriseMall = this.enterpriseMall;
          }
          // 项目管理
          if (item.id === 'projectManage') {
            params.setting[item.id].projectFieldList = this.projectInfo.projectFieldData || []
            params.setting[item.id].ProjectTaskFieldList = this.projectInfo.taskFieldData || []
          }
          // 产品附加组件
          if(item.id == 'productCard') {
            params.setting[item.id].productCardList = this.productCardList || []
          }
        })
        settingCom2.forEach((item, index) => {
          params.setting[item.id] = {
            isOpen: 1,
            order: settingIndex2.length + index + 1,
            title: item.title,
            notShowTitle: item.notShowTitle || false,
          }
        })
        if (settingMall2.length > 0) {
          params.setting[settingMall2[0].id] = {
            isOpen: 1,
            order: settingIndex2.length + settingCom2.length + 1,
            title: settingMall2[0].title,
            notShowTitle: settingMall2[0].notShowTitle || false,
          }
        }

        const needServerDeleFiles = this.$refs.rightComPonentRef?.$refs?.paasApplyTemplateRef?.needServerDeleFiles ?? []
        params.deleteFiles = needServerDeleFiles
        params.tenantId = this.tenantId

        let { code, msg } = await saveSuperCodeTemplate(params)
        if (code === '200') {
          this.$platform.notification({
            type: 'success',
            title: this.$t('common.base.tip.saveSuccess'),
            message: '',
          })
          this.back()
        } else {
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.toast'),
            message: msg,
          })
        }
      } catch (err) {
        console.error(err)
      }
    },
    // 初始化地图
    initMap() {
      const dom = document.getElementById('mapWrapper')
      if (!dom) {
        setTimeout(() => {
          this.initMap()
        }, 500)
        return
      }
      map && map.destroy()
      let longitude = this.comData.attribute.longitude
      let latitude = this.comData.attribute.latitude
      let width = 21
      let height = 28.5

      map = new AMap.Map('mapWrapper', {
        center: [longitude, latitude],
        dragEnable: false, // 禁止滑动
        zoom: 13,
      })

      let icon = new AMap.Icon({
        size: new AMap.Size(width, height),
        image: MAP_MARKER,
        imageSize: new AMap.Size(width, height),
      })

      let marker = new AMap.Marker({
        position: [longitude, latitude],
        icon,
        offset: new AMap.Pixel(-(width / 2), -height),
      })
      map.add(marker)
    },
    // 获取公司信息
    async queryCompanyInfo() {
      const params = {
        tenantId: this.tenantId,
      }
      let { code, data, msg } = await queryCompanyInfo(params)
      if (code === '200') {
        this.comData = _.assign(this.comData, data)
      } else {
        this.$notify.error({
          title: this.$t('common.base.toast'),
          message: msg,
          duration: 2000,
        })
      }
    },
    // 切换配置
    topClick(e) {
      if (e.target.nodeName.toLowerCase() === 'span') {
        const index = parseInt(e.target.dataset.index)
        if (this.topIndex === index) return
        this.topIndex = index
        if (index === 2 && this.comFirst) {
          this.queryCompanyInfo()
        }
        this.nowOption = { name: '', title: '', notShowTitle: false }
        this.selectId = null
      }
    },
    // 获取关联事件
    async queryEventType(id = '') {
      try {
        const params = {
          tenantId: this.tenantId,
          id,
        }
        const { data, code, msg } = await queryEventType(params)
        if (code === '200') {
          if (id === '') {
            this.allEventList = data
            if (
              this.initParams.doorEventType
              && this.initParams.doorEventType.length
            )
              this.queryEventType(this.initParams.id)
            else {
              this.updateEventList();
              this.rightFlag++
            }
          } else {
            this.eventList = data
            if (data) {
              this.eventIdList = data.map((item) => item.id)
            } else {
              this.eventIdList = []
            }
            this.updateEventList();
            this.rightFlag++
          }
        } else {
          this.$notify.error({
            title: this.$t('common.base.toast'),
            message: msg,
            duration: 2000,
          })
        }
      } catch (err) {
        console.error(err)
      }
    },
    /** 查询关联的paas流程 */
    async getSuperCodePaasInfoReq() {
      try {
        const params = {
          tenantId: this.tenantId,
          id: this.initParams.id
        }
        const { data=[], code, msg } = await getSuperCodePaasInfo(params);
        if(code == 200) {
          this.paasList = data || [];
        }
      } catch (err) {
        console.error(err)
      }
    },
    updateCustomerServiceName(val) {
      if (val === 'shb') this.updateWechatServiceUrl('');

      this.customerServiceName = val;
    },
    updateWechatServiceUrl(val) {
      this.wechatServiceUrl = val;
    },
    updateSelfService(obj) {
      if (!obj.key) return;
      this[obj.key] = obj.val;
      this.eventList = this.allEventList.filter((item) =>
        this.eventIdList.find((id) => item.id === id)
      )
      this.updateEventList();
    },
    updateEventList() {
      if (this.progressQuery) this.eventList.push({ name: this.$t('product.setting.qrCodeSet.temComponent.name1'), id: 'progressQuery' });
      if (this.enterpriseMall) this.eventList.push({ name: this.$t('product.setting.qrCodeSet.temComponent.name2'), id: 'enterpriseMall' });
    },
    // 修改规则
    changeEvent(ids) {
      this.eventList = this.allEventList.filter((item) =>
        ids.find((id) => item.id === id)
      )
      this.eventIdList = this.eventList.map((item) => item.id)
      this.updateEventList();
    },
    changePaas(value) {
      this.paasList = value
    },
    // 滚动
    handleScroll: _.debounce(function () {
      if (!this.selectId) return
      this.scrollFlag = true
      this.$nextTick(() => {
        this.scrollFlag = false
        this.calDelStyle()
      })
    }, 200),
    // 计算样式
    calDelStyle() {
      let top
      if (this.selectId === 'productIntroduction')
        top = this.clientRect.top - 70
      else if (this.selectId === 'onlineService') top = this.clientRect.top - 90
      else if (this.selectId === 'selfService') top = this.clientRect.top - 90
      else if (this.selectId.includes('images')) top = this.clientRect.top - 70
      else top = this.clientRect.top
      // 避免删除按钮超出范围看不到
      if(top < 0) top = 0
      let parentHeight = this.$refs.btmCenter?.offsetHeight
      let childHeight = 72 // 因右边删除的悬浮按钮高度不定，所以假定用72来作为高度
      let max = parentHeight ? parentHeight - childHeight : null
      if(max && top > max) top = max
      this.delStyle = `top:${top}px`
    },
    // 删除模块
    delItem(id) {
      if (id !== 'productInformation') {
        this.selectId = null
        const index = this.settingOptions2.findIndex((s) => s.id === id)
        this.settingOptions2.splice(index, 1)
        delete this.imageArray[id]
        let item = this.settingOptions.find((s) => s.id === id)
        if (item) item.dragged = false
        this.nowOption = { name: '', title: '', notShowTitle: false }
      }
    },
    // 手机中选中模块
    selectItem(id, clientRect) {
      this.selectId = id
      this.clientRect = clientRect
      this.nowOption = Object.assign(
        this.nowOption,
        this.settingOptions2.find((item) => item.id === id)
      )
      this.calDelStyle()
      if (id === 'enterpriseInformation') {
        map && map.destroy()
        setTimeout(() => {
          this.initMap()
        }, 0)
      }
    },
    dragClick(leftItem) {
      const item = _.cloneDeep(leftItem);
      if (!item.dragged) {
        leftItem.dragged = !leftItem.id.includes('images')
        if(item.id.includes('images')){
          let imageNewItem = Object.assign({}, item)
          imageNewItem.id = `images${randomString()}`
          this.settingOptions2.push(imageNewItem)
          this.$set(this.imageArray, imageNewItem.id, [])
          this.$nextTick(() => {
            this.$refs[`phone_${imageNewItem.id}`][0].select(imageNewItem.id)
          })
        }else{
          this.settingOptions2.push(item);
          this.$nextTick(() => {
            this.$refs[`phone_${item.id}`][0].select(item.id)
          })
        }
         
        this.settingOptions2[this.settingOptions2.length - 1].side = 'right'
      }
    },
    onMove(e) {
      const element = e.relatedContext.element
      if (element && element.side === 'left') return false
      return true
    },
    moveEnd() {
      this.settingOptions2.forEach((item) => {
        item.side = 'right'
        const leftItem = this.settingOptions.find((left) => item.id === left.id)
        if (leftItem && !leftItem.id.includes('images')) leftItem.dragged = true
      })
    },
    moveEnd2() {
      const index = this.settingOptions2.findIndex(item=>item.id === 'images');
      const imageItem = this.settingOptions.find((item) => item.id === 'images')
      if(this.settingOptions2.find(item=>item.id === 'images')){
        let imageNewItem = Object.assign({}, imageItem);
        imageNewItem.id = `images${randomString()}`
        this.settingOptions2.splice(index, 1, imageNewItem)
        this.$set(this.imageArray, imageNewItem.id, [])
      }else{
        this.settingOptions2.splice(index, 1, imageItem)
        this.$set(this.imageArray, imageItem.id, [])
      }
      this.settingOptions2.forEach((item) => {
        item.side = 'right'
      })
    },
    back() {
      let fromId = window.frameElement.getAttribute('fromid')
      let id = window.frameElement.dataset.id
      this.$platform.closeTab(id)

      // this.$platform.openTab({
      //   id: 'M_SYSTEM',
      //   title: '产品二维码设置',
      //   url: '/setting/productV2/catalog/setting?type=qrcodeSet',
      //   reload: true,
      //   close: true,
      //   fromId,
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductQrcodeSet,
        // titleKey: '产品二维码设置',
        params: 'type=qrcodeSet',
        reload: true,
        fromId
      })
    },
    itemAttrChange([type, valueName, value]) {
      let item = this.settingOptions2.find((item) => item.id === type)
      if (!item) return
      this.$set(item, valueName, value)
    },
    // 小地球回调
    multiLang(calb){
      this.phoneShow = false
      const item = this.settingOptions2.find(
        (item) => item.id === this.nowOption.id
      )
      if (!item) {
        this.$nextTick(() => {
          this.phoneShow = true
        })
        return
      }
      item.displayNameLanguage = calb
      this.nowOption.displayNameLanguage = calb

      this.$nextTick(() => {
        this.phoneShow = true
      })
    }
  },
  components: {
    draggable,
    [phoneContent.name]: phoneContent,
    [rightComponent.name]: rightComponent,
    [ruleDialog.name]: ruleDialog,
    [lastDialog.name]: lastDialog,
  },
}
</script>

<style lang="scss" scoped>
.setting-wrapper {
  ul {
    margin-bottom: 0;
  }
  .setting-top {
    height: 50px;
    color: #fff;
    background: linear-gradient(270deg, $color-primary-light-4, $color-primary-light-6);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 0;

    .top-left {
      padding-left: 20px;
      display: flex;

      .el-button--text {
        color: #fff !important;
      }

      ::v-deep .el-input {
        height: 50px;
        margin-left: 10px;
        border-left: 1px solid #fff;
      }

      ::v-deep .el-input__inner {
        background: none;
        border: none;
        color: #fff !important;
        font-size: 16px;
        border-bottom: 1px dashed #fff;
        margin-left: 10px;
        margin-top: 5px;
      }

      ::v-deep input::-webkit-input-placeholder,textarea::-webkit-input-placeholder {
        color: #eee;
      }
      ::v-deep input:-moz-placeholder, textarea:-moz-placeholder {
        color: #eee;
      }
      ::v-deep input::-moz-placeholder, textarea::-moz-placeholder {
        color: #eee;
      }
      ::v-deep input:-ms-input-placeholder, textarea:-ms-input-placeholder {
        color: #eee;
      }
    }

    .top-center {
      font-size: 16px;
      position: absolute;
      left: 50%;
      margin-left: -240px;
      span {
        display: inline-block;
        width: 160px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        cursor: pointer;
        position: relative;
      }
      .active {
        background-color: rgba(0, 0, 0, 0.1);
      }
      .active:after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        display: block;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 8px solid #f5f5f5;
      }
    }

    .top-right {
      padding-right: 10px;
      ::v-deep .el-button {
        color: $color-main;
      }
    }

    ::v-deep .el-button--text {
      color: #fff;
      font-size: 16px;
    }
  }
  .setting-bar {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    color: #8c8c8c;
    padding-left: 20px;
    background-color: $color-primary-light-1;
    position: relative;

    .bar-center {
      position: absolute;
      left: 50%;
      margin-left: -44px;
    }
    .bar-right {
      width: 25%;
    }
  }
  .setting-bottom {
    padding: 12px;
    height: calc(100vh - 90px);
    display: flex;

    .btm-item {
      height: 100%;
      border-radius: 4px;
      padding: 12px;

      .btm-left-title {
        font-size: 14px;
        font-weight: bold;
      }
    }
    .btm-left {
      width: 25%;
      background-color: #fafafa;
      margin-right: 12px;

      .drag-left {
        display: flex;
        flex-wrap: wrap;

        .drag-left-item {
          width: 30%;
          height: 80px;
          text-align: center;
          font-size: 12px;
          color: $text-color-regular;
          margin-right: 3%;
          cursor: all-scroll;
          box-sizing: border-box;
          border: 1px solid transparent;
          i {
            font-size: 34px;
            color: $color-primary;
          }
        }
        .forbid {
          i {
            color: $text-color-gray;
          }
        }
        .drag-left-item:hover {
          background-color: #fff;
          border: 1px solid $color-border-l1;
          border-radius: 4px;
        }
        .chosen {
          background-color: #fff;
          border: 1px solid $color-border-l1;
          border-radius: 4px;
        }
        .ghost {
          background-color: $bg-color-l2 !important;
          i {
            color: $text-color-gray;
          }
        }
      }
    }
    .btm-right {
      width: 25%;
      min-width: 300px;
      background-color: #fafafa;
      margin-left: 12px;
      padding-right: 0;
    }
    .btm-center {
      flex-grow: 1;
      padding: 12px 0;
      position: relative;
      overflow: hidden;

      .btm-center-phone {
        width: 320px;
        height: 100%;
        overflow-y: auto;
        margin: 0 auto;
        padding: 8px;
        border: 1px solid $color-border-l1;
        border-radius: 8px;
        background-color: $bg-color-l2;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);

        .drag-right-wrap {
          height: 100%;

          .drag-right {
            display: block;
            height: 100%;
            position: relative;
          }
        }
      }
      .btm-center-name {
        cursor: pointer;
        position: absolute;
        top: 12px;
        left: calc(50% + 165px);
        max-width: 116px;
        background-color: #fff;
        border: 1px solid $color-border-l1;
        border-radius: 4px;
        padding: 5px;
      }
    }
  }
}
</style>
